package com.huyucheng.todolist

import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.huyucheng.todolist.utils.executeBackground
import com.huyucheng.todolist.utils.executeMain
import com.huyucheng.todolist.utils.getValue
import kotlinx.android.synthetic.main.fragment_addtodo.*
import kotlinx.android.synthetic.main.fragment_todolist.*
import kotlinx.android.synthetic.main.todo_item.view.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async

class AddTodoFragment : Fragment() {

    companion object {
        val TAG: String = "AddTodoFragment"
    }

    private var todoAdded = false

    lateinit var todoDao: TodoDao

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        todoDao = AppDatabase.getDatabase(this.activity?.applicationContext).todoDao()
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_addtodo, container, false)
        return view
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // Add todo and update database
        add_btn.setOnClickListener {
            if (!TextUtils.isEmpty(view.todo_content.text)) {
                val newTodo = Todo(todo_content.text.toString(), 0, todo_priority.selectedItem as Int)
                // coroutine
                val insertResultDeferred = GlobalScope.async { todoDao.insertTodo(newTodo) }

                // check whether the todo is added to the DB
                executeMain {
                    if (insertResultDeferred.await() > 0) {
                        Toast.makeText(this.context, "Todo Added! ", Toast.LENGTH_SHORT).show()
                        todoAdded = true
                    } else {
                        Toast.makeText(this.context, "Failed to add Todo! ", Toast.LENGTH_SHORT).show()
                    }
                }
                view.todo_content.text = ""
            } else {
                Toast.makeText(
                    this.context,
                    "The Content Should Not Be Empty! ",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
        return_btn.setOnClickListener {
            replaceFragment()
        }

        val priorities = arrayListOf(0, 1, 2, 3)

        val priorityAdapter = ArrayAdapter<Int>(activity!!, R.layout.item_select, priorities)
        priorityAdapter.setDropDownViewResource(R.layout.item_drop)
        todo_priority.adapter = priorityAdapter
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        todoAdded = false
    }

    private fun replaceFragment() {
        val transaction = fragmentManager?.beginTransaction()
        var fragment = fragmentManager?.findFragmentByTag("TodoListFragment")
        if (transaction == null) {
            Log.e(TAG, "replaceFragment: failed to begin fragment transaction")
            return
        }
        if (fragment == null) {
            transaction.add(R.id.fragment_container, TodoListFragment())
        } else {
            if (todoAdded) {
                (fragment as TodoListFragment).reloadDataFromDB()
            }
            transaction.show(fragment)
        }
        transaction.hide(this)
        transaction.addToBackStack(null)
        transaction.commit()
    }
}